import com.alibaba.fastjson.JSONObject;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    private static String root = HT.Path(System.getProperty("user.dir"));
    private static Config config = new Config();
    private static String api = "";
    private static Proxy proxy = null;

    public static void main(String[] args) throws Exception {
        HT.Log("加载配置……");
        String source = String.valueOf(config.getString("library"));
        if (source.equals("re")) {
            api = "https://pixiv.re/";
        }
        if (source.equals("cat")) {
            api = "https://pixiv.cat/";
        }
        if (config.getBoolean("proxy.source"))
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getString("proxy.host"), config.getInteger("proxy.port")));
        while (true) {
            String[] ids = new String[]{};
            String input = HT.Input("请输入Code：");
            Pattern pattern = Pattern.compile("^[\\d+,?]+$");
            Matcher matcher = pattern.matcher(input);
            if (matcher.matches()) {
                ids = input.split(",");
            } else {
                HT.Log("格式错误，请重新输入……");
                continue;
            }
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(ids.length);
            for (String id : ids) {
                Quest quest = new Quest(proxy, api + id + ".jpg", HT.Path(root + id));
                executor.execute(quest);
            }
            executor.shutdown();
            while (executor.getCompletedTaskCount() < ids.length) {
                HT.Log("下载中:" + executor.getPoolSize() + "，等待中" + executor.getQueue().size() + "，已下载" + executor.getCompletedTaskCount());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            HT.Log("下载中:" + executor.getPoolSize() + "，等待中" + executor.getQueue().size() + "，已下载" + executor.getCompletedTaskCount());
            HT.Log("下载完毕!");
            System.out.println("====================");
        }
    }
}
